<?php


namespace App\Service\ExternalAPI;

use EchoPHP\Facades\Log;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/**
 * 51job简历接口
 * @package App\Service\ExternalAPI
 */
class VApi {

    private $_source = 'rpopro';

    const LANG_CN = 'c';        //中文简历
    const LANG_EN = 'e';        //英文简历

    /**
     * 接口地址
     * @var
     */
    protected $host;
    /**
     * 签名密钥
     * @var
     */
    protected $signKey;
    /**
     * 客户端标识
     * @var
     */
    protected $source;
    /**
     * 接口版本
     * @var
     */
    protected $version;
    /**
     * 接口超时时间
     * @var
     */
    protected $timeout;

    protected $errorMsg;

    /**
     * 初始化接口
     * VApi constructor.
     * @param $accountId
     * @throws \Exception
     */
    public function __construct() {
        $options = config('extraapi.vapi', []);
        $this->host = $options['host'];
        $this->version = $options['version'];
        $this->source = $options['source'];
        $this->signKey = $options['key'];
        $this->timeout = $options['timeout'];
    }

    /**
     * 获取简历内容（从简历json格式解析为相关数组）
     * @param $accountId
     * @param $resumeId
     * @param string $lang
     * @return array|bool|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getResumeContent($accountId, $resumeId, $lang = self::LANG_CN) {
        $requestPath = '/resume.php';
        $getData = array(
            'query' => 'jsonresume',
        );
        $postData = array(
            'accountid' => $accountId,
            'resumeid' => $resumeId,
            'isenglish' => $lang,
        );
        $content = $this->request($requestPath, $getData, $postData);
        if (is_null($content)) {
            return [];
        }
        $content = $content['jsoncontent'];
        return json_decode($content, true);
    }

    /**
     * 获取简历头像
     * @param $accountId
     * @param $resumeId
     * @param string $lang
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getResumeAvatar($accountId, $resumeId, $lang = self::LANG_CN) {
        $requestPath = '/resume.php';
        $getData = array(
            'query' => 'avatar',
        );
        $postData = array(
            'accountid' => $accountId,
            'resumeid' => $resumeId
        );
        $content = $this->request($requestPath, $getData, $postData);
        if (is_null($content) || !isset($content['hasAvatar']) || $content['hasAvatar'] != '1') {
            return '';
        }

        $content = $content['content'];
        return $content;
    }

    /**
     * 获取简历附件
     * @param $accountId
     * @param $resumeId
     * @param string $lang
     * @return array|bool|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getResumeAttachment($accountId, $resumeId, $attachId) {
        $requestPath = '/resume.php';
        $getData = array(
            'query' => 'attachment',
        );
        $postData = array(
            'accountid' => $accountId,
            'resumeid' => $resumeId,
            'attachid' => $attachId
        );
        $content = $this->request($requestPath, $getData, $postData);
        //["attachname"]=> string(12) "我的作品" ["attachtype"]=> string(1) "1" ["attachurl"]=> string(0) "" ["attachfile"]
        return $content;
    }


    /**
     * 整理请求参数，发起请求并整理返回结果
     * @param $requestPath
     * @param $getData
     * @param $postData
     * @param boolean $autoEncode 自动html编码
     * @param boolean $convertToGBK 是否需要转换为gbk编码
     * @return array|bool|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function request($requestPath, $getData, $postData) {
        $getData['source'] = $this->source;
        if (!isset($getData['version'])) {
            $getData['version'] = $this->version;
        }
        $query = http_build_query($getData);
        $requestUrl = $requestPath . '?' . $query;
        $data = json_encode($postData);
        $sign = $this->generateSign($data);

        $client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);


        try {
            $response = $client->request('POST', $requestUrl, [
                'form_params' => [
                    'data' => $data,
                    'sign' => $sign
                ],
            ]);
            $content = $response->getBody()->getContents();
            $content = json_decode($content, true);
            if (!isset($content['status'])) {
                throw new Exception('接口未返回status字段');
            }
            if ($content['status'] != 1) {
                throw new Exception('简历接口调用失败,status[' . $content['status'] . '];message[' . $content['message'] . ']');
            }
            return $content['resultbody'];
        } catch (Exception $e) {
            $this->errorMsg = $e->getMessage();
            Log::error($this->errorMsg, [
                'requestUrl' => $requestUrl,
                'data' => $data,
                'sign' => $sign,
            ]);
            return null;
        }
    }

    /**
     * 生成接口签名
     * @param string $data post参数json字符串
     * @return string
     */
    private function generateSign($data) {
        return md5(hash('sha256', $data . date('YmdG') . $this->signKey));
    }


}